package com.example.memo_app.acties;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.memo_app.R;
import com.example.memo_app.dao.MemoBean;
import com.example.memo_app.util.GlideEngine;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.xuexiang.xui.widget.button.ButtonView;
import com.xuexiang.xui.widget.edittext.MultiLineEditText;
import com.xuexiang.xui.widget.edittext.ValidatorEditText;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;


/**
 * 主页面
 */
public class MainActivity extends AppCompatActivity {

    private RecyclerView rv;
    private FloatingActionButton fab;
    private List<MemoBean> memoBeanList = new ArrayList<>();
    private AlertDialog alertDialog;
    private Spinner mSpinnerSelect;


    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private int currentPosition = 0;

    private void initData() {
        //查询所有备忘录数据
        BmobQuery<MemoBean> queryType = new BmobQuery<>();
        queryType.addWhereEqualTo("type", currentPosition);
        queryType.findObjects(new FindListener<MemoBean>() {
            @Override
            public void done(List<MemoBean> list, BmobException e) {
                if (e == null) {
                    memoBeanList.clear();
                    memoBeanList.addAll(list);
                    //集合反转
                    Collections.reverse(memoBeanList);
                    rv.setAdapter(new MemoAdapter());
                }
            }
        });
    }

    private void initView() {
        rv = (RecyclerView) findViewById(R.id.rv);
        //悬浮添加按钮
        fab = (FloatingActionButton) findViewById(R.id.fab);
        rv.setLayoutManager(new LinearLayoutManager(this));
        fab.setOnClickListener(v -> showDialog(new MemoBean(), false));
        mSpinnerSelect = findViewById(R.id.spinner_select);
        mSpinnerSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentPosition = position;
                initData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //显示的图片列表
    List<String> paths = new ArrayList<>();

    //显示添加对话框
    private void showDialog(MemoBean memoBean, boolean isEdit) {
        if (isEdit) {
            paths.addAll(memoBean.getPath());
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_add, null);
        builder.setView(view);
        ValidatorEditText etTitle;
        MultiLineEditText etContent;
        RecyclerView rvPic;
        ButtonView btnBack;
        ButtonView btnFinish;
        etTitle = (ValidatorEditText) view.findViewById(R.id.et_title);
        Spinner et_tag = (Spinner) view.findViewById(R.id.spinner);
        etContent = (MultiLineEditText) view.findViewById(R.id.et_content);
        rvPic = (RecyclerView) view.findViewById(R.id.rv_pic);
        btnBack = (ButtonView) view.findViewById(R.id.btn_back);
        ImageView iv_add = (ImageView) view.findViewById(R.id.iv_add);
        btnFinish = (ButtonView) view.findViewById(R.id.btn_finish);

        etTitle.setText(memoBean.getTitle());
        etContent.setContentText(memoBean.getMessage());

        et_tag.setSelection(memoBean.getType());

        btnFinish.setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            if (title.isEmpty()) {
                Toast.makeText(this, "标题不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            memoBean.setTitle(title);

            int type = et_tag.getSelectedItemPosition();
            memoBean.setType(type);

            String contentText = etContent.getContentText();
            if (contentText.isEmpty()) {
                Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            memoBean.setMessage(contentText);
            memoBean.setPath(paths);
            if (isEdit) {
                memoBean.update(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                            alertDialog.dismiss();
                            paths.clear();
                            initData();
                        } else {
                            Toast.makeText(MainActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } else {
                memoBean.save(new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        if (e == null) {
                            Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                            alertDialog.dismiss();
                            paths.clear();
                            initData();
                        } else {
                            Toast.makeText(MainActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

        });
        MyPicAdapter myAdapter = new MyPicAdapter();
        rvPic.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        rvPic.setAdapter(myAdapter);
        iv_add.setOnClickListener(v -> addPic(myAdapter));
        //关闭对话框
        btnBack.setOnClickListener(v -> alertDialog.dismiss());
        alertDialog = builder.create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
        //设置对话框背景透明
        alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    }

    //添加图片
    private void addPic(MyPicAdapter adapter) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .isEnableCrop(true)
                .maxSelectNum(1)
                .rotateEnabled(false)
                .isDragFrame(true)
                .cropImageWideHigh(10000, 10000)
                .freeStyleCropEnabled(true)
                .hideBottomControls(false)
                .imageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        if (result != null && result.size() > 0) {
                            LocalMedia localMedia = result.get(0);
                            if (localMedia.isCut()) {
                                paths.add(localMedia.getCutPath());
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void onCancel() {
                        // onCancel Callback
                    }
                });

    }


    //备忘录列表适配器
    class MemoAdapter extends RecyclerView.Adapter<MemoViewHolder> {

        private AlertDialog alertDialogEdit;

        @NonNull
        @NotNull
        @Override
        public MemoViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, parent, false);
            return new MemoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull @NotNull MemoViewHolder holder, int position) {
            MemoBean bean = memoBeanList.get(position);
            holder.mTvContent.setText(bean.getMessage());
            holder.mTvTitle.setText(bean.getTitle());
            holder.tv_time.setText(bean.getCreatedAt());
            List<String> path = bean.getPath();
            if (path.size() > 0) {
                Glide.with(MainActivity.this).load(path.get(position)).into(holder.mIvFirst);
            } else {
                holder.mIvFirst.setVisibility(View.GONE);
            }

            holder.itemView.setOnLongClickListener(v -> {
                showEditDialog(position);
                return true;
            });

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转到详情页面
                    Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                    intent.putExtra("data", memoBeanList.get(position));
                    startActivity(intent);
                }
            });

        }

        @Override
        public int getItemCount() {
            return memoBeanList.size();
        }


        private void showEditDialog(int position) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_edit, null);
            builder.setView(view);
            TextView mTvDelete;
            TextView mTvEdit;
            TextView mTvCancel;
            mTvDelete = view.findViewById(R.id.tv_delete);
            mTvEdit = view.findViewById(R.id.tv_edit);
            mTvCancel = view.findViewById(R.id.tv_cancel);
            mTvCancel.setOnClickListener(v -> alertDialogEdit.dismiss());

            mTvEdit.setOnClickListener(v -> {
                alertDialogEdit.dismiss();
                showDialog(memoBeanList.get(position), true);
            });

            mTvDelete.setOnClickListener(v -> {
                //本地集合移除图片
                MemoBean bean = memoBeanList.remove(position);
                //刷新列表
                notifyDataSetChanged();
                //网络数据库删除图片
                bean.delete(new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                            //重新获取数据
                            initData();
                        }
                    }
                });
                alertDialogEdit.dismiss();
            });

            alertDialogEdit = builder.create();
            alertDialogEdit.show();

        }
    }

    static class MemoViewHolder extends RecyclerView.ViewHolder {

        TextView mTvTitle;
        TextView mTvContent;
        TextView tv_time;
        ImageView mIvFirst;


        public MemoViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            mTvTitle = itemView.findViewById(R.id.tv_title);
            mTvContent = itemView.findViewById(R.id.tv_content);
            mIvFirst = itemView.findViewById(R.id.iv_first);
            tv_time = itemView.findViewById(R.id.tv_time);
        }
    }

    class MyPicAdapter extends RecyclerView.Adapter<MyPicViewHolder> {

        @NonNull
        @NotNull
        @Override
        public MyPicViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_iamgeview, parent, false);
            return new MyPicViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull @NotNull MyPicViewHolder holder, int position) {
            //显示图片
            Glide.with(MainActivity.this).load(paths.get(position)).into(holder.view);
//            holder.view.setBackgroundResource(R.mipmap.ic_launcher);
            holder.view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    paths.remove(position);
                    notifyDataSetChanged();
                    return true;
                }
            });
        }

        @Override
        public int getItemCount() {
            return paths.size();
        }
    }


    static class MyPicViewHolder extends RecyclerView.ViewHolder {

        private ImageView view;

        public MyPicViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            view = (ImageView) itemView;
        }
    }
}
